package com.ruoyi.ora.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.dict.DevicePermission;
import com.ruoyi.common.enums.dict.DeviceUserStatus;
import com.ruoyi.common.enums.dict.UserMessageType;
import com.ruoyi.common.enums.dict.VoiceRecordStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ThreadManager;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.ora.domain.*;
import com.ruoyi.ora.factory.AiFactory;
import com.ruoyi.ora.factory.VoiceTranslatFactory;
import com.ruoyi.ora.mapper.DeviceMapper;
import com.ruoyi.ora.mapper.VoiceRecordMapper;
import com.ruoyi.ora.service.IDeviceService;
import com.ruoyi.ora.service.IDeviceUserService;
import com.ruoyi.ora.service.IUserMessageService;
import com.ruoyi.ora.service.IVoiceRecordService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 语音转写记录Service业务层处理
 * 
 * @author liuwp
 * @date 2024-11-14
 */
@Service
public class VoiceRecordServiceImpl implements IVoiceRecordService
{
    @Autowired
    private VoiceRecordMapper voiceRecordMapper;
    @Autowired
    private IUserMessageService userMessageService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceUserService deviceUserService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private DeviceMapper deviceMapper;

    /**
     * 查询语音转写记录
     *
     * @param id 语音转写记录主键
     * @return 语音转写记录
     */
    @Override
    public VoiceRecord selectVoiceRecordById(Long id)
    {
        return voiceRecordMapper.selectVoiceRecordById(id);
    }

    /**
     * 查询语音转写记录列表
     *
     * @param voiceRecord 语音转写记录
     * @return 语音转写记录
     */
    @Override
    public List<VoiceRecord> selectVoiceRecordList(VoiceRecord voiceRecord)
    {
        return voiceRecordMapper.selectVoiceRecordList(voiceRecord);
    }

    @Override
    public List<VoiceRecord> selectVoiceRecordListCollection(VoiceRecord voiceRecord) {
        return voiceRecordMapper.selectVoiceRecordListCollection(voiceRecord);
    }

    @Override
    public List<VoiceRecord> selectVoiceRecordListDeviceUser(VoiceRecord voiceRecord) {
        return voiceRecordMapper.selectVoiceRecordListDeviceUser(voiceRecord);
    }

    /**
     * 根据业务主键查询一条记录：语音转写记录
     *
     * @param voiceRecord 语音转写记录
     * @return 语音转写记录
     */
    @Override
    public VoiceRecord selectOneVoiceRecord(VoiceRecord voiceRecord)
    {
        return voiceRecordMapper.selectOneVoiceRecord(voiceRecord);
    }

    /**
     * 新增语音转写记录
     *
     * @param voiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int insertVoiceRecord(VoiceRecord voiceRecord)
    {
        voiceRecord.setCreateTime(DateUtils.getNowDate());
        return voiceRecordMapper.insertVoiceRecord(voiceRecord);
    }

    /**
     * 修改语音转写记录
     *
     * @param voiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int updateVoiceRecord(VoiceRecord voiceRecord)
    {
        return voiceRecordMapper.updateVoiceRecord(voiceRecord);
    }

    @Override
    public int updateVoiceRecordCondition(VoiceRecord voiceRecord, VoiceRecord voiceRecordCondition)
    {
        return voiceRecordMapper.updateVoiceRecordCondition(voiceRecord, voiceRecordCondition);
    }

    /**
     * 批量删除语音转写记录
     *
     * @param ids 需要删除的语音转写记录主键
     * @return 结果
     */
    @Override
    public int deleteVoiceRecordByIds(Long[] ids)
    {
        return voiceRecordMapper.deleteVoiceRecordByIds(ids);
    }

    /**
     * 删除语音转写记录信息
     *
     * @param id 语音转写记录主键
     * @return 结果
     */
    @Override
    public int deleteVoiceRecordById(Long id)
    {
        return voiceRecordMapper.deleteVoiceRecordById(id);
    }

    /**
     * 条件删除语音转写记录
     *
     * @param voiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int deleteVoiceRecordByCondition(VoiceRecord voiceRecord)
    {
        return voiceRecordMapper.deleteVoiceRecordByCondition(voiceRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public VoiceRecord voiceRecordUpload(VoiceRecord voiceRecord, MultipartFile file) {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            voiceRecord.setVoicePath(fileName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        voiceRecord.setStatus(VoiceRecordStatus.TRANSLATING.getValue());
        voiceRecord.setAiPlatform(BizConstants.TRAN_MODEL.getValue());
        insertVoiceRecord(voiceRecord);

        if (voiceRecord.getDeviceId() != null){
            Device device = deviceService.selectDeviceById(voiceRecord.getDeviceId());
            if (device != null){
                // 获取设备的管理员用户
                List<DeviceUser> deviceUsers = deviceUserService.selectDeviceUserList(Builder.of(DeviceUser::new)
                        .with(DeviceUser::setDeviceId, voiceRecord.getDeviceId())
                        .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                        .with(DeviceUser::setDevicePermission, DevicePermission.ADMIN.getValue())
                        .build());
                for (DeviceUser deviceUser : deviceUsers) {
                    userMessageService.insertUserMessage(Builder.of(UserMessage::new)
                            .with(UserMessage::setUserId, deviceUser.getUserId())
                            .with(UserMessage::setMsgType, UserMessageType.VOICE_UPLOAD.getValue())
                            .with(UserMessage::setAssetsId1, voiceRecord.getId().toString())
                            .with(UserMessage::setMsgTitle, "设备【"+deviceUser.getDeviceName()+"】有新的录音").build());
                }
            }
            // TODO 验证是否不有转写时间，如果没有则不转写了
//        SysUser sysUser = sysUserMapper.querySysUserById(SecurityUtils.getUserId());  //已从用户表中挪到设备表中
            long surplusDuration = device.getSurplusDuration() == null ? 0 : device.getSurplusDuration(); //剩余转写时长
            if(surplusDuration != -1){
                if(surplusDuration > 1){
                    // 添加到转写
                    ThreadManager.me().execute(() -> {
                        VoiceTranslatFactory.build(voiceRecord.getAiPlatform().intValue()).voiceTranslat(voiceRecord);
                        long voiceDuration = voiceRecord.getVoiceDuration() != null ? voiceRecord.getVoiceDuration() : 0L;//语音转写时长
                        long duration = 0;
                        if(surplusDuration > voiceDuration){
                            duration = surplusDuration - voiceDuration;
                        }
//                // 更新用户会员信息
//                sysUserMapper.updateUser(Builder.of(SysUser::new)
//                        .with(SysUser::setUserId, sysUser.getUserId())
//                        // 这里假设会员时长需要累减，根据实际业务调整
//                        .with(SysUser::setSurplusDuration, duration)
//                        .build());
                        deviceMapper.updateDevice(Builder.of(Device::new)
                                .with(Device::setId, voiceRecord.getDeviceId())
                                // 这里假设会员时长需要累加，根据实际业务调整
                                .with(Device::setSurplusDuration, duration)
                                .build());
                    });
                }else {
                    voiceRecord.setStatus(VoiceRecordStatus.OUT_OF_BALANCE.getValue());
                    updateVoiceRecord(voiceRecord);
                    throw new RuntimeException("剩余转写时间不足");
                }
            }

        }else {
            throw new RuntimeException("参数错误");
        }
        return voiceRecord;
    }

    @Override
    public void tranFinishHandle(VoiceRecord voiceRecord, VoiceTranModel voiceTranModel) {
        try {
            if (voiceTranModel != null && Constants.SUCCESS.equalsIgnoreCase(String.valueOf(voiceTranModel.getCode()))){
                // TODO 再次判断转写时长， 如果超出剩余时间则直接改为  OUT_OF_BALANCE  如果时长够用则把用户时间减掉

                /// TODO 扣除剩余转写时间
//                Long userId = SecurityUtils.getUserId();
//                SysUser user = userService.selectUserById(userId);
//                if (user != null){
//                    // 转写时长
//                    Long transDuration = Long.parseLong(voiceTranModel.getTotalDuration());
//                    // 剩余时长
//                    Long surplusDuration = user.getSurplusDuration();
//                    if (surplusDuration < transDuration){
//                        // 余额不足
//                        voiceRecord.setStatus(VoiceRecordStatus.OUT_OF_BALANCE.getValue());
//                        updateVoiceRecord(voiceRecord);
//                        return;
//                    }
//                    // 扣除时长
//                    user.setSurplusDuration(surplusDuration - transDuration);
//                    userService.updateUser(user);
//                }

                if (StringUtils.isNotEmpty(voiceTranModel.getText())){
                    voiceRecord.setVoiceContent(voiceTranModel.getText());
                    voiceRecord.setVoiceTransliterate(JSONObject.toJSONString(voiceTranModel));

                    // 标题
                    String title = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请给以上内容做一个10字左右的标题，直接返回结果即可。不要加任何其他内容");
                    String voiceTitle = title.contains("error")?voiceRecord.getVoiceContent().length()>10?voiceRecord.getVoiceContent().substring(0, 10):voiceRecord.getVoiceContent():title;
                    voiceRecord.setVoiceTitle(voiceTitle);

                    // 摘要
                    String summarize = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请给以上内容做一个20字左右的总结");
                    String voiceSummarize = summarize.contains("error")?voiceRecord.getVoiceContent().length()>20?voiceRecord.getVoiceContent().substring(0, 20):voiceRecord.getVoiceContent():summarize;
                    voiceRecord.setVoiceSummarize(voiceSummarize);

                    // 待办
                    String agency = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请根据以为内容生成出待办的清单，把时间和事项分开，时间使用年月日格式，不要使用明天后天等格式，使用json格式输出，直接json格式就行，不需要加markdown格式，字段名使用英文，例如：{\"time\":\"明天\",\"thing\":\"陪父母去爬山\"}，如果没有合适的事项直接返回空，不要随便举例");
                    String voiceAgency = agency.contains("error")?null:agency;
                    voiceRecord.setVoiceAgency(voiceAgency);

                    try {
                        if (voiceTranModel.getSegments() != null && voiceTranModel.getSegments().size() > 0){
                            VoiceSegment lastItem = voiceTranModel.getSegments().get(voiceTranModel.getSegments().size() - 1);
                            Long roundedEnd = (long) Math.ceil(Double.valueOf(lastItem.getEnd()));
                            voiceRecord.setVoiceDuration(roundedEnd);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                voiceRecord.setStatus(VoiceRecordStatus.TRANSLATED.getValue());

            }else {
                voiceRecord.setStatus(VoiceRecordStatus.ERROR.getValue());
            }
        }catch (Exception e){
            e.printStackTrace();
            voiceRecord.setStatus(VoiceRecordStatus.ERROR.getValue());
        }
        updateVoiceRecord(voiceRecord);
    }

}
